package cn.itcast.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {
    // spring 初始化完成时会调用这个方法
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置publisher-return 回调
        rabbitTemplate.setReturnCallback(
                new RabbitTemplate.ReturnCallback() {
                    @Override
                    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                        // 如果是延迟消息，忽略
                        Integer receivedDelay = message.getMessageProperties().getReceivedDelay();
                        if (receivedDelay > 0) {
                            log.info("[这是个延迟消息]");
                            return;
                        }
                        log.error("[消息转发到队列时失败]响应码: {} 原因: {} 交换机: {} 路由key: {} 消息: {}", replyCode, replyText, exchange, routingKey, message);
                    }
                }
        );
    }

    // lambda实现
//    @Override
//    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        // 获取RabbitTemplate
//        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
//        // 设置ReturnCallback
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
//            // 投递失败，记录日志
//            log.info("消息路由到队列时失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
//                    replyCode, replyText, exchange, routingKey, message.toString());
//            // 如果有业务需要，可以重发消息
//        });
//    }
}
